package com.mexico.inloancash.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.R;
import com.mexico.inloancash.activity.IndiaCerActivity;
import com.mexico.inloancash.activity.IndiaLoginActivity;
import com.mexico.inloancash.bean.BaseBean;
import com.mexico.inloancash.dialog.mIndiaChooseDialog;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.india_interfacedai.IndiaChooseAddressInterface;
import com.mexico.inloancash.india_interfacedai.IndiaDealDialogInterface;
import com.mexico.inloancash.utils.Auth;
import com.mexico.inloancash.utils.FileUtils;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.MyToast;
import com.mexico.inloancash.utils.MyUtils;
import com.mexico.inloancash.utils.permission.RxPermissions;
import com.mexico.inloancash.utils.permission.SchedulerTransformer;
import com.google.gson.Gson;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.KeyGenerator;
import com.qiniu.android.storage.Recorder;
import com.qiniu.android.storage.UploadManager;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static android.app.Activity.RESULT_OK;

/**
 * 职位信息
 */
public class IndiaFourthStepAuthFragment extends BaseFragment implements IndiaChooseAddressInterface, IndiaDealDialogInterface {

    @BindView(R.id.have_work_text)
    TextView mHaveWorkText;

    @BindView(R.id.have_work_linear)
    LinearLayout mIndia_HaveWorkLinear;

    @BindView(R.id.company_name)
    EditText mIndia_CompanyName;

    @BindView(R.id.work_city)
    EditText mIndia_WorkCity;

    @BindView(R.id.tv_company_address)
    EditText mIndia_Company_Address;

    @BindView(R.id.tv_company_region)
    EditText mIndia_Company_Region;

    @BindView(R.id.company_phone)
    EditText mIndia_Company_Phone;

    @BindView(R.id.salary)
    EditText mIndia_Salary;

    @BindView(R.id.job_type)
    TextView mIndia_JobType;

    @BindView(R.id.company_linear)
    LinearLayout mIndia_Company_Linear;

    @BindView(R.id.payday)
    TextView mIndia_Payday;

    @BindView(R.id.wage_linear)
    LinearLayout mIndia_WageLinear;

    @BindView(R.id.work_length)
    TextView mIndia_WorkLength;

    @BindView(R.id.work_length_linear)
    LinearLayout mIndia_WorkLength_Linear;

    @BindView(R.id.prove)
    ImageView mIndia_Prove;

    @BindView(R.id.submit)
    Button mIndia_Submit;

    @BindView(R.id.tv_month_income)
    EditText mIndia_TvInCome;//月收入

    Unbinder unbinder;

    private View four;
    private IndiaCerActivity activity;//用于修改对应标题
    private mIndiaChooseDialog dialog;
    private String imageUrl = "";
    private UploadManager mUploadManager;
    private Recorder recorder;
    private KeyGenerator keyGen;
    Configuration mConfig;
    private String mUpToken;

    /*String accessKey = "kFiJToSdmLlsn2ttg-L8_X51Cu4oFialS-9qIKtB";
    String secretKey = "MGYWxZcIKcDcxzxJfDiar42ERXg1Wtimz-ixCl0U";*/

    String accessKey = "lb5ntuPzvl6BoSqL5yato8Pqwg5WXoPHGVzTktIt";

    String secretKey = "7i3g_SDTFCvJ-TYs3FBfCJJtki8Rp2hYfNVIK908";

    //String bucket = "ynimage001";
    String bucket = "north-us";
    /**
     * 调起拍照
     */
    private File currentImageFile;
    Uri uri;
    private File file = null;
    File mZhengFile = null;
    private List<String> mLength;
    private List<String> mJobList;
    private List<String> mWorkList;

    public IndiaFourthStepAuthFragment(IndiaCerActivity activity) {
        this.activity = activity;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        four = inflater.inflate(R.layout.india_activity_four_view_auths_layout_fragment, container, false);
        activity.mIndiaUpdateTitle("Work information");
        unbinder = ButterKnife.bind(this, four);
        mConfig = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .recorder(null)           // recorder分片上传时，已上传片记录器。默认null
                .recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zoneNa0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        Auth auth = Auth.create(accessKey, secretKey);
        mUpToken = auth.uploadToken(bucket);
        mHaveWorkText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                set_Jump_Button();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        return four;
    }

    @OnClick({R.id.have_work_linear, R.id.wage_linear, R.id.work_length_linear, R.id.company_linear, R.id.prove, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.have_work_linear:
                //工作类型 没用这个
                mWorkList = new ArrayList<>();
                mWorkList.add("FULL");
                mWorkList.add("NO_WORK");
                mWorkList.add("PART");
                mWorkList.add("SELF");
                dialog = new mIndiaChooseDialog(getContext(), this, "Work Ndustry", mWorkList, "work");
                dialog.show();
                break;
            case R.id.company_linear:
                //工作类型
                mJobList = new ArrayList<>();
                mJobList.add("Accountant / Finance Officer");
                mJobList.add("Customer service");
                mJobList.add("Engineer");
                mJobList.add("Executive");
                mJobList.add("General Administration");
                mJobList.add("Technologies");
                mJobList.add("Consultant/Analyst");
                mJobList.add("Store");
                mJobList.add("Teacher");
                mJobList.add("Military");
                mJobList.add("Retired");
                mJobList.add("Student");
                mJobList.add("Businessman");
                mJobList.add("Policeman");
                mJobList.add("Farmer");
                mJobList.add("Fisherman");
                mJobList.add("Creator");
                mJobList.add("Doctor");
                mJobList.add("Medical staff (nurses, midwives, etc.)");
                mJobList.add("Law (lawyer, notary)");
                mJobList.add("Hospitality and restaurant (chef, waiter, etc.)");
                mJobList.add("Investigator");
                mJobList.add("Designer");
                mJobList.add("Architect");
                mJobList.add("Art workers (artists, musicians, painters, etc.)");
                mJobList.add("Security");
                mJobList.add("Runners");
                mJobList.add("Distributor");
                mJobList.add("Air transport (pilot, stewardess)");
                mJobList.add("Maritime transport (Captain, ABK)");
                mJobList.add("Ground transportation (driver, driver)");
                mJobList.add("Workers (factory workers, constitution workers, agricultural workers)");
                mJobList.add("Supir & Carpentry and craftsmen (carpenters, leather craftsmen, etc.)");
                mJobList.add("Housewife");
                mJobList.add("Informal workers (domestic helpers, assistants, etc.)");
                mJobList.add("National Office / National Organization");
                mJobList.add("Government officials / state institutions (other than state officials / organizations)");
                mJobList.add("Others");
                dialog = new mIndiaChooseDialog(getContext(), this, "Kind of job", mJobList, "job");
                dialog.show();
                break;
            case R.id.wage_linear:
                //发薪日
                List<String> date = new ArrayList<>();
                for (int i = 1; i < 31; i++) {
                    date.add(i + "");
                }
                dialog = new mIndiaChooseDialog(getContext(), this, "Día de paga", date, "date");
                dialog.show();
                break;
            case R.id.work_length_linear:
                //工作年限
                mLength = new ArrayList<>();
                mLength.add("Within 1 year");
                mLength.add("1 ～ 3 years");
                mLength.add("3 ～ 10 years");
                mLength.add("More than 10 years");
                mLength.add("unknown");
                dialog = new mIndiaChooseDialog(getContext(), this, "Years of work", mLength, "length");
                dialog.show();
                break;
            case R.id.prove:
                //PhotoDialog dialog1 = new PhotoDialog(getActivity(), FourthStepAuthFragment.this);
                //dialog1.show();
                choose_Jump_Work_Card();
                break;
            case R.id.submit:
                check_Empty();
                break;
        }
    }

    /**
     * 设置按钮变色
     */
    public void set_Jump_Button() {
    }

    /**
     * 判断未填项
     */

    public void check_Empty() {
        if (TextUtils.isEmpty(mIndia_CompanyName.getText().toString().trim())) {
            MyToast.show(getContext(), "Company name cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(mIndia_Company_Phone.getText().toString().trim())) {
            MyToast.show(getContext(), "Company phone number cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(mIndia_TvInCome.getText().toString().trim())) {
            MyToast.show(getContext(), "Monthly income cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(mIndia_WorkCity.getText().toString().trim())) {
            MyToast.show(getContext(), "Work city cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(mIndia_Company_Address.getText().toString().trim())) {
            MyToast.show(getContext(), "Address cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(mIndia_JobType.getText().toString().trim())) {
            MyToast.show(getContext(), "Please select the type of work");
            return;
        }

        loading.show();
        String token = mUpToken;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key1 = "icon_3" + sdf.format(new Date());
        mUploadManager = new UploadManager(mConfig);
        File myFile = mZhengFile;
        if (null == myFile) {
            savingJob();
        } else {
            mUploadManager.put(myFile, key1, token,
                    (key, info, res) -> {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            imageUrl = key;
                            if (TextUtils.isEmpty(imageUrl)) {
                                return;
                            }
                            savingJob();
                        } else {
                            loading.dismiss();
                            MyToast.show(activity, "Image upload failed, please check internet connection");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                    }, null);
        }
    }


    /**
     * 上传工作证明
     */
    public void savingJob() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> saveWork;
        saveWork = api.saveWork(
                MyPreferencesManager.getString("token", ""),
                MyApplication.source,
                mIndia_CompanyName.getText().toString().trim(),
                mIndia_Company_Phone.getText().toString().trim(),
                String.valueOf(mJobList.indexOf(mIndia_JobType.getText().toString().trim())),
                mIndia_TvInCome.getText().toString().trim(),
                mIndia_WorkCity.getText().toString().trim(),
                mIndia_Company_Address.getText().toString().trim()
        );
        saveWork.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    BaseBean baseBean = new Gson().fromJson(response.body(), BaseBean.class);
                    if (baseBean.getCode() == 200) {
                        activity.finish();
                        MyToast.show(activity, "Information saved successfully");
                    } else if (baseBean.getCode() == 401) {
                        Intent intent = new Intent(getContext(), IndiaLoginActivity.class);
                        startActivity(intent);
                    }
                }
                loading.dismiss();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading.dismiss();
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void choose(String type, String string) {
        if (type.equals("job")) {
            mIndia_JobType.setText(string);
        } else if (type.equals("length")) {
            mIndia_WorkLength.setText(string);
        } else if (type.equals("date")) {
            mIndia_Payday.setText(string);
        } else if (type.equals("inCome")) {
            //月收入
            mIndia_TvInCome.setText(string);
        }
    }

    @Override
    public void doPlay() {
        new RxPermissions(activity)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .compose(new SchedulerTransformer<>())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        jumpToCamera();
                    } else {
                        MyToast.show(getContext(), "Please open the memory card read-write, camera permission");
                    }
                });
    }

    @Override
    public void choose() {
        new RxPermissions(activity)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .compose(new SchedulerTransformer<Boolean>())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 1);
                    } else {
                        MyToast.show(getContext(), "Please open the memory card read-write, camera permission");
                    }
                });
    }


    /**
     * 调取拍照
     */
    public void jumpToCamera() {
        File dir = new File(Environment.getExternalStorageDirectory(), "myimage");//在sd下创建文件夹myimage；Environment.getExternalStorageDirectory()得到SD卡路径文件
        if (!dir.exists()) {    //exists()判断文件是否存在，不存在则创建文件
            dir.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式在android中，创建文件时，文件名中不能包含“：”冒号
        String filename = df.format(new Date());
        currentImageFile = new File(dir, filename + ".jpg");
        if (!currentImageFile.exists()) {
            try {
                currentImageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT < 24) {
            currentImageFile = new File(dir, filename + ".jpg");
            // 从文件中创建uri
            uri = Uri.fromFile(currentImageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            // 兼容Android 7.0 使用共享文件的形式
            ContentValues contentValues = new ContentValues();
            uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        startActivityForResult(intent, 2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1://文件中选择照片
                if (data == null) {
                    return;
                }
                uri = data.getData();
                file = new File(MyUtils.getPath(uri, getActivity()));
                loading.show();
//                Avatar();
                break;
            case 2://拍照完成回调
                if (Build.VERSION.SDK_INT < 24) {
                    if (null == currentImageFile) {
                        return;
                    }
                    file = currentImageFile;
                } else {
                    file = new File(MyUtils.getPath(uri, getActivity()));
                    if (null == file) {
                        return;
                    }
                }
                loading.show();
//                Avatar();
                break;
            case REQUEST_CODE_WORK_CARD:
                if (resultCode == RESULT_OK) {
                    Log.d("loan", "onActivityResult:" + REQUEST_CODE_WORK_CARD);
                    List<Uri> results = Matisse.obtainResult(data);
                    if (results != null && !results.isEmpty()) {
                        compressJump_Work_Card(results.get(0));
                        loading.show();
                    }
                }
                break;
        }
    }

    /**
     * 压缩工作证明
     */
    public void compressJump_Work_Card(Uri uri) {
        String filePath = FileUtils.getRealFilePath(getContext(), uri);
        Luban.with(getContext())
                .load(new File(filePath))
                .ignoreBy(20)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(final File file) {
                        mZhengFile = file;
                        Glide.with(getActivity()).load(mZhengFile).placeholder(R.mipmap.india_gocash_picture_pic_camera).into(mIndia_Prove);
                        loading.dismiss();
                        set_Jump_Button();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        loading.dismiss();
                    }
                }).launch();
    }

    public static final int REQUEST_CODE_WORK_CARD = 1002;

    /**
     * 选择工作证明
     */
    private void choose_Jump_Work_Card() {
        Log.d("loan", "chooseWorkCard");
        new RxPermissions(getActivity())
                .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Matisse.from(this)
                                .choose(EnumSet.of(MimeType.JPEG, MimeType.PNG))
                                .showSingleMediaType(true)
                                .maxSelectable(1)
                                .maxOriginalSize(10)
                                .countable(false)
                                //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                                .capture(true)
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//强制让照片选择页面竖屏显示 横屏拍照会有bug
                                .captureStrategy(new CaptureStrategy(true, "PhotoPickerIndia"))
                                .thumbnailScale(0.85f)
                                .showPreview(false)
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//强制让照片选择页面竖屏显示 横屏拍照会有bug
                                .imageEngine(new GlideEngine())
                                .theme(R.style.MyMatisse)
                                .forResult(REQUEST_CODE_WORK_CARD);
                    }
                });
    }
}
